import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

/// 获取原生存的用户数据 工具类
class KeyValueNativeUtil {
  static const _methodChannelName = 'flutter.keqiang.com/kv';

  static const _platformMethod = MethodChannel(_methodChannelName);

  /// 设置bool类型
  static Future<bool> setBool(
      {required String key, required bool value}) async {
    try {
      if (Platform.isIOS) {
        String? result = await _platformMethod
            .invokeMethod('setBool', {'key': key, 'value': value ? '1' : '0'});
        return result == '1' ? true : false;
      }
      return await _platformMethod
          .invokeMethod('setBool', {'key': key, 'value': value});
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
    return false;
  }

  /// 获取bool类型
  static Future<bool> getBool({required String key, bool? defValue}) async {
    try {
      if (Platform.isIOS) {
        String? value = await _platformMethod
            .invokeMethod('getBool', {'key': key, 'defaultValue': defValue});
        if (value == "1") {
          return true;
        } else {
          return false;
        }
      }
      return await _platformMethod
          .invokeMethod('getBool', {'key': key, 'defaultValue': defValue});
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
    return defValue ?? false;
  }

  /// 获取String类型
  static Future<bool> setString({required String key, String? value}) async {
    try {
      if (Platform.isIOS) {
        String? res = await _platformMethod
            .invokeMethod('setString', {'key': key, 'value': value});
        if (res == "1") {
          return true;
        } else {
          return false;
        }
      }
      return await _platformMethod
          .invokeMethod('setString', {'key': key, 'value': value});
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
    return false;
  }

  /// 获取String类型
  static Future<String?> getString(
      {required String key, String? defValue}) async {
    try {
      return await _platformMethod
          .invokeMethod('getString', {'key': key, 'defaultValue': defValue});
    } on PlatformException catch (e) {
      debugPrint(e.message);
      return defValue;
    }
  }

  /// 获取Int类型
  static Future<int> getInt({required String key, int? defValue}) async {
    try {
      if (Platform.isIOS) {
        String? value = await _platformMethod
            .invokeMethod('getBool', {'key': key, 'defaultValue': defValue});
        if (value != null) {
          return int.parse(value);
        } else {
          return 0;
        }
      }
      return await _platformMethod
          .invokeMethod('getInt', {'key': key, 'defaultValue': defValue});
    } on PlatformException catch (e) {
      debugPrint(e.message);
      return defValue ?? 0;
    }
  }
}
